/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require('mongoose');
var async = require('async');
const DataModel = require('../models/news.model');
const Comment = require('../models/comment.model');

//增
exports.create = function(req,res,next){
    const dataModel = new DataModel(req.body);
    dataModel.save()
        .then(data=>{
            res.json(data);
        })
}

//查，获取
exports.get = function(req,res,next){
    var id = req.params.id;

    DataModel.findById(id,function(err,data){
        res.json(data);
    })
}

//改
exports.update = function(req,res,next){
    const id = req.params.id;

    DataModel.findByIdAndUpdate(id, {$set: req.body},{new:false})
        .then(data=>{
            res.json(data);
        })
}

//删
exports.remove = function(req,res,next){
    const id = req.params.id;
    DataModel.findByIdAndRemove(id,function(err,data){
        res.json(data);
    })
};

//列表
exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 10;

    var queryCondition = {};
    if(req.body.title && req.body.title.trim().length>0){
        title = req.body.title;
        queryCondition = {
            "title" : new RegExp(title,'i')
        }
    }
    if(req.body.cateId && req.body.cateId.trim().length>0){
        cateId = req.body.cateId;
        // Object.assign对象合并
        queryCondition = Object.assign(queryCondition,
            {
                cateId: cateId
            }
        )
    }
    DataModel.paginate(queryCondition,{sort:{_id:-1},page:parseInt(page),limit:parseInt(rows)},function(err,result){

        //评论数获取
        async.map(result.docs,function(news,callback){
            Comment.count({commentId: news._id},function(err,count){
                if(err){
                    return;
                }else{
                    news.commentCount = count;
                    callback(null,news);
                }
            })
        },function(err){
            result.rows = result.docs;
            delete result.docs;
            res.json(result)
        })
    });
};

exports.deletes = function(req,res,next){
    var ids = req.body.ids;
    if(ids.length>0){
        DataModel.remove({_id:{$in:ids.split(',')}})
            .then(data=>{
                res.json({"msg":"deletes success","status":200});
            })
    }else{
        res.json({"msg":"deletes fail","status":404});
    }
};